<?php

namespace App\Listeners;

use App\Events\OrderEvent;
use App\Models\product\ProductSonModel;
use App\Service\users\AccountRecordService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class OrderUserAmountSave
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(OrderEvent $event): void
    {
        $orderInfo = $event->data;

        $proSon = ProductSonModel::leftJoin('product', 'product.id', '=', 'product_son.product_id')
            ->leftJoin('product_popularize', 'product_popularize.id', '=', 'product_son.popularize_id')
            ->select('product.product_title', 'product_popularize.popularize_name')
            ->where('product_son.id', $orderInfo['product_id'])
            ->first();
        if (!$proSon) {
            Log::error('事件订单生成失败：商品不存在');
            return;
        }

        $title = $proSon->product_title . '(' . $proSon->popularize_name . ')';

        match ($orderInfo['order_status']) {
            // 已支付
            1 => AccountRecordService::instance()->createAmountRecord(
                $orderInfo['uid'],
                $orderInfo['commission'],
                AccountRecordService::USER_CREDIT,
                AccountRecordService::TYPE_ORDER,
                $orderInfo['id'],
                $title . '-支付成功，增加待入账' . $orderInfo['commission'] . '元',
                'user'
            ),
            // 订单已完成
            2 => [
                AccountRecordService::instance()->createAmountRecord(
                    $orderInfo['uid'],
                    $orderInfo['commission'] == 0 ? 0 : 0 - $orderInfo['commission'],
                    AccountRecordService::USER_CREDIT,
                    AccountRecordService::TYPE_ORDER,
                    $orderInfo['id'],
                    $title . '-订单完成，扣除待入账' . $orderInfo['commission'] . '元',
                    'user'
                ),
                AccountRecordService::instance()->createAmountRecord(
                    $orderInfo['uid'],
                    $orderInfo['commission'],
                    AccountRecordService::USER_AMOUNT,
                    AccountRecordService::TYPE_ORDER,
                    $orderInfo['id'],
                    $title . '-订单完成，增加余额' . $orderInfo['commission'] . '元',
                    'user'
                )
            ],
            // 订单已退款
            4 => AccountRecordService::instance()->createAmountRecord(
                $orderInfo['uid'],
                $orderInfo['commission'] == 0 ? 0 : 0 - $orderInfo['commission'],
                AccountRecordService::USER_CREDIT,
                AccountRecordService::TYPE_ORDER,
                $orderInfo['id'],
                $title . '-已退款，扣除待入账' . $orderInfo['commission'] . '元',
                'user'
            ),
            default => ''
        };
    }
}
